package com.qc.wintrax.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.qc.wintrax.R;
import com.qc.wintrax.WTApplication;
import com.qc.wintrax.activity.ElevationActivity;
import com.qc.wintrax.activity.LineToCollectActivity;
import com.qc.wintrax.activity.MoreMarkerActivity;
import com.qc.wintrax.model.Distance;
import com.qc.wintrax.utils.GpsCorrect;
import com.qc.wintrax.utils.IntentUtil;
import com.qc.wintrax.utils.LogUtil;
import com.qc.wintrax.utils.TimerUtil;
import com.qc.wintrax.utils.ToastUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import greendao.LineName;
import greendao.MapInfo;
import greendao.MarkerInfo;

import static android.app.Activity.RESULT_OK;

/**
 * @author xiaobaodou
 * @Description:(线路采集) create at  2016/7/14 17:00
 **/
public class LineFragment extends BaseFragment implements LocationSource, AMapLocationListener {

    @Bind(R.id.back_imge)
    ImageView backImge;
    @Bind(R.id.title_edit)
    EditText titleEdit;
    @Bind(R.id.toal_time)
    TextView toalTime;
    @Bind(R.id.distance_txt)
    TextView distanceTxt;
    @Bind(R.id.speed_txt)
    TextView speedTxt;
    @Bind(R.id.elevation_img)
    ImageView elevationImg;
    @Bind(R.id.map)
    MapView mapView;
    @Bind(R.id.start_img)
    ImageView startImg;
    @Bind(R.id.cancel_img)
    ImageView cancelImg;
    @Bind(R.id.puse_img)
    ImageView puseImg;
    @Bind(R.id.gn_layout)
    LinearLayout gnLayout;
    @Bind(R.id.chronometer)
    Chronometer chronometer;
    @Bind(R.id.haiba_txt)
    TextView haibaTxt;

    private AMap aMap;
    private Marker marker;// 定位雷达小图标
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private double longitude;
    private double latitude;
    private List<LatLng> points = new ArrayList<LatLng>();
    private List<Distance> distanceList = new ArrayList<Distance>();
    private double a;
    private double b;
    private double address;
    private double alldistance;
    private LatLng startLatlng;
    private Marker markers;
    private ArrayList<MarkerOptions> markerList = new ArrayList<MarkerOptions>();
    private ArrayList<Marker> mList = new ArrayList<Marker>();
    private LatLng mlatlng;
    private List<MapInfo> mapInfoList = new ArrayList<MapInfo>();
    private List<MapInfo> newmapInfoList = new ArrayList<MapInfo>();
    private List<MarkerInfo> markerInfos = new ArrayList<MarkerInfo>();
    private List<MarkerInfo> newmarkerInfos = new ArrayList<MarkerInfo>();
    private List<Double> altiList = new ArrayList<Double>();

    private int chTag = 0;
    private String name;
    private long rangeTime = 0;
    private boolean PAUSE = false;
    private int cc = -1;
    //是否是第一次定位
    private boolean isFirstLatLng = true;
    //以前的定位点
    private LatLng oldLatLng;
    private String gpsStr;
    private double haiba;
    private double speed;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_line, container, false);
        ButterKnife.bind(this, view);
        initView();
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (isVisible() && isResumed()) {

            initView();
            gnLayout.setVisibility(View.GONE);
            startImg.setVisibility(View.VISIBLE);
            toalTime.setText("00:00:00");
            distanceTxt.setText("0.00");
            speedTxt.setText("0'00''");
        }
    }

    public void initView() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        LogUtil.e(str);
        titleEdit.setText(str);

        chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                cc++;
                LogUtil.e("得到的计时---" + cc);
                toalTime.setText(TimerUtil.FormatMiss((int) cc));
            }
        });

        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.moveCamera(CameraUpdateFactory.zoomTo(30));
        }
        titleEdit.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                titleEdit.setFocusable(true);
                titleEdit.setFocusableInTouchMode(true);
                titleEdit.requestFocus();
                return false;
            }
        });
        aMap.setOnMapLongClickListener(new AMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                mlatlng = latLng;
                latitude = mlatlng.latitude;
                longitude = mlatlng.longitude;
                LogUtil.e("获取的经纬度----" + latitude + "-----" + longitude);
                Intent intent = new Intent(getActivity(), MoreMarkerActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                for (int i = 0; i < mList.size(); i++) {
                    if (marker.equals(mList.get(i))) {
                        if (aMap != null) {
//                            if (markerTAG == 0) {
////                                jumpPoint(marker, i);
//                                Toast.makeText(context, "跳到相机功能", Toast.LENGTH_SHORT).show();
//                                LogUtil.e("跳到相机功能" + i);
//                                markerTAG = 1;
//                            } else {
//                                Toast.makeText(context, "查看图片", Toast.LENGTH_SHORT).show();
//                                LogUtil.e("查看图片");
//                                markerTAG = 0;
//                            }
                        }
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                String biaoji = data.getStringExtra("biaoji");
                Bitmap bm = data.getParcelableExtra("Bitmap");
//                List<Bitmap> newBitmapList = (List<Bitmap>) data.getSerializableExtra("BitmapList");
//                LogUtil.e("获取的标记是----" + biaoji);
                setMarker(mlatlng, biaoji,bm);
                MarkerInfo markerInfo = new MarkerInfo();
                markerInfo.setMarker_latitude(latitude);
                markerInfo.setMarker_longitude(longitude);
                markerInfo.setMarker_titleName(biaoji);
                markerInfos.add(markerInfo);
                gnLayout.setVisibility(View.GONE);
                startImg.setVisibility(View.VISIBLE);

            }
        }
    }

    private void setMarker(LatLng latlon, String title,Bitmap sbitmap) {
//        aMap.clear();
        deactivate();
//        View markerView = LayoutInflater.from(context).inflate(R.layout.marker_view, null);
        // 设置标注物的图片
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.map_zuobiao);
        BitmapDescriptor bitmaps = BitmapDescriptorFactory.fromBitmap(sbitmap);
        // 构建MarkerOption，用于在地图上添加Marker
        MarkerOptions options = new MarkerOptions().position(latlon).icon(bitmaps).title(title);
        // 在地图上添加Marker，并显示
        options.snippet(latlon.toString());
        options.draggable(true);
        options.perspective(true);
        options.draggable(true);
        markerList.add(options);
        markers = aMap.addMarker(options);
        mList.add(markers);
        aMap.addMarkers(markerList, true);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
//        LogUtil.e("Line+222222222222");
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {

//                marker.setPosition(new LatLng(amapLocation.getLatitude(), amapLocation
//                        .getLongitude()));// 定位雷达小图标
                float bearing = aMap.getCameraPosition().bearing;
                aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                a = amapLocation.getLatitude();//获取纬度
                b = amapLocation.getLongitude();//获取经度
//                double[] adjusLat = GpsCorrect.transform(a, b);
//                double aa = adjusLat[0];
//                double bb = adjusLat[1];
                LatLng newLatLng = new LatLng(a, b);
                LogUtil.e("结束获取的经newLatLng--a--" + newLatLng);
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
//                LogUtil.e("结束获取的经纬度--a--" + aa);
//                LogUtil.e("结束获取的经纬度--b--" + bb);
                gpsStr = amapLocation.getProvider();
                LogUtil.e("开始获取的类型--gpsStr--" + gpsStr);
                if (isFirstLatLng) {
                    //记录第一次的定位信息
                    oldLatLng = newLatLng;
                    isFirstLatLng = false;
//                    LogUtil.e("结束获取的经纬度--a--" + aa);
//                    LogUtil.e("结束获取的经纬度--b--" + bb);
                }
                if (oldLatLng.latitude != newLatLng.latitude || oldLatLng.longitude != newLatLng.longitude) {
                    LogUtil.e("结束获取的经oldLatLng--b--" + oldLatLng);
//                    points.add(newLatLng);
//                    aMap.addPolyline(new PolylineOptions().addAll(points).width(15).
//                    geodesic(true).color(Color.rgb(18, 184, 246)));
                    aMap.addPolyline(new PolylineOptions().add(oldLatLng, newLatLng)
                            .geodesic(true).width(15).color(Color.rgb(18, 184, 246)));
                    // 计算量坐标点距离
                    address = AMapUtils.calculateLineDistance(oldLatLng, newLatLng);
                    LogUtil.e("获取的address --address--" + address);
                    oldLatLng = newLatLng;
                    if (gpsStr.equals("gps")) {
                        haiba = amapLocation.getAltitude();
//                        LogUtil.e("获取的海拔高度--haiba--" + haiba);
                        speed = amapLocation.getSpeed();
                        LogUtil.e("获取的sud --speed--" + speed);
                    } else if (gpsStr.equals("lbs")) {
                        speed = address / 3;
                        LogUtil.e("获取的sud --speed--" + speed);
                    } else {
                        speedTxt.setText("0'0''");
                    }
                    double xx = 1000 / speed / 60.0;
                    BigDecimal bdl = new BigDecimal(xx);
                    double f1 = bdl.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    speedTxt.setText(f1 + "");
                    BigDecimal bd = new BigDecimal(address);
                    double disStr = bd.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
                    alldistance = alldistance + disStr;
                    distanceTxt.setText(alldistance / 1000 + "");
                    LogUtil.e("结束获取的距离--disStr-0000-" + alldistance);
                    altiList.add(haiba);
                    haibaTxt.setText(haiba + "");
                    MapInfo mapInfo = new MapInfo();
                    mapInfo.setMap_title(name);
                    mapInfo.setMap_altitude(haiba);
                    mapInfo.setMap_latitude(a);
                    mapInfo.setMap_longitude(b);
                    mapInfoList.add(mapInfo);
//                    LogUtil.e("结束获取的长度--mapInfoList--" + mapInfoList.size());
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);  //定位时间
                }
            }
        } else {
            String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
            Log.e("AmapErr", errText);
        }
//        }
    }

    private void setUpMap() {
        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
//        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.point1));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.point2));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.point3));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.mipmap.point4));
////        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point5));
////        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point6));
//        marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icons(giflist).period(20));
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.point1));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
//        myLocationStyle.anchor(0.5f, 0.5f);//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式 ，可以由定位 LOCATION_TYPE_LOCATE、
        // 跟随 LOCATION_TYPE_MAP_FOLLOW 或地图根据面向方向旋转 LOCATION_TYPE_MAP_ROTATE
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().isCompassEnabled();
        aMap.getUiSettings().setScaleControlsEnabled(true);
        aMap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        aMap.getUiSettings().setCompassEnabled(true);
        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getActivity());
            mLocationOption = new AMapLocationClientOption();
            // 设置定位监听
            mlocationClient.setLocationListener(this);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            /**
             * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
             * 注意：只有在高精度模式下的单次定位有效，其他方式无效
             */
            mLocationOption.setGpsFirst(true);
            // 设置发送定位请求的时间间隔,最小值为1000ms,1秒更新一次定位信息
            mLocationOption.setInterval(3000);
            // 设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mapView.onDestroy();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.back_imge, R.id.elevation_img, R.id.start_img, R.id.cancel_img, R.id.puse_img})
    public void onClick(View view) {
        name = titleEdit.getText().toString();
        switch (view.getId()) {
            case R.id.back_imge:
                mapView.onPause();
                getActivity().finish();
                break;
            case R.id.elevation_img:
                if (altiList.size() > 5) {
                    String dis = distanceTxt.getText().toString();
                    WTApplication.getInstance().setConfig("dis", dis);
                    WTApplication.getInstance().setInfoList(mapInfoList);
                    WTApplication.getInstance().setAltList(altiList);
                    IntentUtil.startActivity(ElevationActivity.class);

                } else {
                    ToastUtil.show(getActivity(), "还没有获取到有效的海拔数据！");
                }
                break;
            case R.id.start_img:
                if (chTag == 1) {
                    chronometer.setBase(SystemClock.elapsedRealtime() - rangeTime - 3);
                    chronometer.start();
                } else if (chTag == 0) {
                    rangeTime = 0;
                    // 设置开始讲时时间
                    chronometer.setBase(SystemClock.elapsedRealtime());
                    // 开始记时
                    chronometer.start();
                    chTag = 0;
                }
                startImg.setVisibility(View.GONE);
                gnLayout.setVisibility(View.VISIBLE);
                WTApplication.getInstance().setConfig("name", name);
                setUpMap();
                PAUSE = true;
                break;
            case R.id.puse_img:
                mapView.onPause();
                deactivate();
                chTag = 1;
                if (PAUSE == true) {
                    rangeTime = SystemClock.elapsedRealtime() - chronometer.getBase();
                    chronometer.stop();

                    PAUSE = false;
                }
                gnLayout.setVisibility(View.GONE);
                startImg.setVisibility(View.VISIBLE);
                break;
            case R.id.cancel_img:
                if (mapInfoList != null && mapInfoList.size() > 0) {
                    chronometer.stop();
                    mapView.onPause();
                    deactivate();
                    LineName lineName = new LineName();
                    lineName.setMap_distance(distanceTxt.getText().toString());
                    lineName.setMap_totalTime(toalTime.getText().toString());
                    lineName.setMap_title(name);
                    long id = WTApplication.getGSDaoSession().getLineNameDao().insert(lineName);
                    ToastUtil.show(getActivity(), "获取的主键" + id);
                    for (int i = 0; i < mapInfoList.size(); i++) {
                        MapInfo mapInfo = mapInfoList.get(i);
                        if (mapInfo != null) {
                            double a = mapInfo.getMap_latitude();
                            double b = mapInfo.getMap_longitude();
                            double haiba = mapInfo.getMap_altitude();
                            String name = mapInfo.getMap_title();
                            MapInfo mapInfo1 = new MapInfo();
                            mapInfo1.setMap_latitude(a);
                            mapInfo1.setMap_longitude(b);
                            mapInfo1.setMap_title(name);
                            mapInfo1.setLine_id(id);
                            if (haiba > 0) {
                                mapInfo1.setMap_altitude(haiba);
                            }
                            newmapInfoList.add(mapInfo1);
                        }
                    }
                    WTApplication.getGSDaoSession().getMapInfoDao().insertInTx(newmapInfoList);
                    for (int a = 0; a < markerInfos.size(); a++) {
                        MarkerInfo markerInfo = markerInfos.get(a);
                        double aa = markerInfo.getMarker_latitude();
                        double bb = markerInfo.getMarker_longitude();
                        String names = markerInfo.getMarker_titleName();
                        MarkerInfo info = new MarkerInfo();
                        info.setLine_id(id);
                        info.setMarker_latitude(aa);
                        info.setMarker_longitude(bb);
                        info.setMarker_titleName(names);
                        newmarkerInfos.add(info);
                    }
                    WTApplication.getGSDaoSession().getMarkerInfoDao().insertInTx(newmarkerInfos);
//                    WTApplication.getInstance().finishActivity();
                    LineToCollectActivity activity = (LineToCollectActivity) getActivity();
                    activity.initFragment(1);
                } else {
                    ToastUtil.show(getActivity(), "还没有采集到有效的数据！");
                }
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }
}
